package com.example.geoaimavlink_android.activity.fragment

import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import com.example.geoaimavlink_android.R
import com.example.geoaimavlink_android.activity.view.FilePickerFullScreen
import com.geoai.mavlink.geoainet.airlink.AirlinkManager
import com.geoai.mavlink.geoainet.airlink.interfaces.IMcuOtaUpgradeListener
import com.geoai.mavlink.geoainet.airlink.module.dsp.P301DModule
import com.geoai.mavlink.geoainet.airlink.module.rc.K3RModule
import com.geoai.mavlink.geoainet.base.mavlinkcore.engine.GEOAIError
import com.geoai.mavlink.geoainet.system.interfaces.IFirmwareUpgradeListener
import com.geoai.mavlink.util.process.data.ProcessTag
import com.github.gzuliyujiang.filepicker.ExplorerConfig
import com.github.gzuliyujiang.filepicker.annotation.ExplorerMode
import kotlinx.android.synthetic.main.frag_firmware_upgrade.btn_select_upgrade_files
import kotlinx.android.synthetic.main.frag_firmware_upgrade.btn_start_upgrade
import kotlinx.android.synthetic.main.frag_firmware_upgrade.btn_start_upgrade_mcu
import kotlinx.android.synthetic.main.frag_firmware_upgrade.btn_start_upgrade_wireless
import kotlinx.android.synthetic.main.frag_firmware_upgrade.tv_firmware_file_path
import kotlinx.android.synthetic.main.frag_firmware_upgrade.tv_upgrade_process
import kotlinx.android.synthetic.main.frag_firmware_upgrade.tv_upgrade_progress
import kotlinx.android.synthetic.main.frag_firmware_upgrade.tv_upgrade_state
import java.io.File

class FirmwareUpgradeFragment : BaseFragment() {
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return View.inflate(context, R.layout.frag_firmware_upgrade, null)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initSDK()
        initView()
    }

    private fun initView() {
        btn_select_upgrade_files.setOnClickListener {
            FilePickerFullScreen(requireActivity()).apply {
                setExplorerConfig(ExplorerConfig(context).apply {
                    rootDir = context.getExternalFilesDir(null)
                    isLoadAsync = false
                    explorerMode = ExplorerMode.FILE
                    setOnFilePickedListener {
                        view?.findViewById<TextView>(R.id.tv_firmware_file_path)?.text = it.absolutePath
                    }
                })
                show()
            }
        }

        btn_start_upgrade.setOnClickListener {
            getProduct()?.systemManager?.startModuleFirmwareUpgrade(tv_firmware_file_path.text.toString(), object : IFirmwareUpgradeListener{
                override fun onStep(processTag: ProcessTag?) {
                    tv_upgrade_process?.text = processTag?.tag?:"null tag"
                }

                override fun onPercentage(percentage: Float) {
                    tv_upgrade_progress?.text = percentage.toString()
                }

                override fun onResult(isSuccess: Boolean, geoaiError: GEOAIError?) {
                    showToast(geoaiError?.description?:"success")
                }
            }) { info -> mainHandler.post { tv_upgrade_state?.text = format(gson.toJson(info)) } }
        }

        btn_start_upgrade_wireless.setOnClickListener {
            val dsp = AirlinkManager.getInstance().dsp
            if (dsp is P301DModule) {
                dsp.startWirelessFirmwareUpgrade(tv_firmware_file_path.text.toString(), object : IFirmwareUpgradeListener{
                    override fun onStep(processTag: ProcessTag?) {
                        activity?.runOnUiThread {
                            tv_upgrade_state?.text = "step: ${processTag?.tag}"
                        }
                    }

                    override fun onPercentage(percentage: Float) {
                        activity?.runOnUiThread {
                            tv_upgrade_state?.text = percentage.toString()
                        }
                    }

                    override fun onResult(isSuccess: Boolean, geoaiError: GEOAIError?) {
                        activity?.runOnUiThread {
                            tv_upgrade_state?.text = "result: " + isSuccess + "::" + geoaiError?.description
                        }
                    }
                })
            }
        }

        btn_start_upgrade_mcu.setOnClickListener {
            val rc = AirlinkManager.getInstance().rc
            if (rc is K3RModule) {
                rc.startMcuOTAUpgrade(File(tv_firmware_file_path.text.toString()), object : IMcuOtaUpgradeListener{
                    override fun onStart() {
                        activity?.runOnUiThread {
                            tv_upgrade_state?.text = "start mcu update"
                        }
                    }

                    override fun onProgress(progress: Int) {
                        activity?.runOnUiThread {
                            tv_upgrade_state?.text = progress.toString()
                        }
                    }

                    override fun onSuccess() {
                        activity?.runOnUiThread {
                            tv_upgrade_state?.text = "success"
                        }
                    }

                    override fun onFail(error: String?) {
                        activity?.runOnUiThread {
                            tv_upgrade_state?.text = "fail: $error"
                        }
                    }
                })
            }
        }
    }

    private fun initSDK() {
        msdkInfoVm.msdkInfo.observe(viewLifecycleOwner) {
            if (it.isAircraftConnected) {
            }
        }
    }
}